<?php
apf_require_class("Bll_BLL");
apf_require_class("Bll_Attendance_DailyReport");
apf_require_class("Bll_Attendance_UserInfo");
apf_require_class("Bll_Attendance_Role");

class Bll_Attendance_Audit extends BLL{

    private $user_info;
    private $boss_id;
    private $passurl = "<a href ='http://kq.corp.anjuke.com/audit/'>审批</a>(http://kq.corp.anjuke.com/audit/)";

    /**
     * 得到所有未审批的列表
     * @param int $user_id
     * @param int $page
     * @param int $offset
     * @param int $where
     */
    public function get_unaudit_list($user_id,$page,$offset,$where=""){
        $data = array();
        if(!$user_id){
            return $data;
        }
        $where["(r_user_id=$user_id AND audit_status=0)  OR (b_user_id=$user_id AND audit_status=1) AND 1=?"] = 1;
        $where["status"]='未审核';
        $data = $this->get_defaut_dao()->find($where,'apply_time_ext DESC ',$page,$offset);
        if(!empty($data)){
            $uids = array();
            foreach($data as $val){
                $uids[]=$val['user_id'];
            }
            $uids=array_unique($uids);
            $_u_where[" user_id IN(".implode(',',$uids).") AND 1=?"]=1;
            $user_bll = new Bll_Attendance_UserInfo();
            $tmpuser_data = $user_bll->get_user_by_condition($_u_where);
            $user_data = array();
            foreach($tmpuser_data as $val){
                $user_data[$val['user_id']]=$val;
            }
            foreach($data as $k=> $val){
                if(isset($user_data[$val['user_id']])){
                    $val = array_merge($val,$user_data[$val['user_id']]);
                }
                $data[$k]=$val;
            }
        }
        return array('rows'=>$data);
    }
    /**
     * 得到所有审批的列表,如果是一级审批人的也可能看到二级审批人还没有审批的请假
     * @param int $user_id
     * @param int $page
     * @param int $offset
     * @param int $where
     */
    public function get_audit_list($user_id,$page,$offset,$where="",$start,$end){
        $data = array(
            'count'=>0,
            'rows'=>array()
        );
        if(!$user_id){
            return $data;
        }
        if(!empty($where['co_name'])){
            $_user_where["code LIKE '%{$where['co_name']}%' OR name LIKE '%{$where['co_name']}%' AND 1=?"] = 1;
            $tmp_data = $user_bll->get_user_by_condition($_user_where);
            if(empty($tmp_data)){
                return $data;
            }
            $uids=array();
            foreach($tmp_data as $val){
                $uids[] = $val['user_id'];
            }
            $_where[" user_id IN(".implode(',',$uids).") AND 1=?"]=1;
        }
        if(!empty($where['start']) && !empty($where['end'])){
            $where['start'].=" 00:00:00";
            $where['end'].=" 23:59:59";
            $_where["end_time>={$where['start']} AND start_time<={$where['end']} AND 1=?"] = 1;
        }
        //需要两级审批一级审批通过,记录还是未审批
        $_where["(r_user_id=$user_id AND (audit_status=1 OR status IN('已批准','已驳回')) AND 1=? ) OR (b_user_id=$user_id AND status IN('已批准','已驳回'))"] = 1;

        $count = $this->get_defaut_dao()->find_count($_where);
        if(!$count){
            return $data;
        }
        $data = $this->get_defaut_dao()->find($_where,'apply_time_ext DESC ',$page,$offset);
        $uids = array();
        foreach($data as $val){
            $uids[]=$val['user_id'];
        }
        $uids=array_unique($uids);
        $_u_where[" user_id IN(".implode(',',$uids).") AND 1=?"]=1;
        $user_bll = new Bll_Attendance_UserInfo();
        $tmpuser_data = $user_bll->get_user_by_condition($_u_where);
        $user_data = array();
        foreach($tmpuser_data as $val){
            $user_data[$val['user_id']]=$val;
        }
        foreach($data as $k=> $val){
            if(isset($user_data[$val['user_id']])){
                $val = array_merge($val,$user_data[$val['user_id']]);
            }
            $data[$k]=$val;
        }
        return array('count'=>$count,'rows'=>$data);
    }
    /**
     * 管理员根据id获取
     */
    public function get_list($user_id,$page,$offset,$where=""){
        $data = array();

        if(!$user_id){
            return $data;
        }
        //是否有查找
        $who = trim($where);
        if($who !=""){
            $and  = " and ((u.name like '%{$where}%') or u.code like '%{$where}%')";
        }
        else{
            $and = '';
        }

        //对hr做特殊处理
        apf_require_class("Bll_Attendance_UserInfo");
        $bll_user = new Bll_Attendance_UserInfo();
        $role = $bll_user->get_user_role($user_id);
        if($role[$user_id]['role_id'] == 3 && !empty($and)){
            $sql = "select u.name,u.code,u.department_name,u.department_id,l.start_time,l.end_time,
                l.type,l.id,l.leave_reason,l.leave_desc,l.r_user_id,l.b_user_id,l.leave_time,l.apply_time_ext
                from leave_record l left join
                user_info u on l.user_id = u.user_id
                where l.status = '未审核' $and
                order by l.id desc
                limit $offset,$page
                ";
        } else {
        $sql = "select a.*,u.user_id,u.name,u.code,u.department_name,u.department_id,l.start_time,l.end_time,
                l.type,l.id,l.leave_reason,l.leave_desc,l.r_user_id,l.b_user_id,l.leave_time,l.apply_time_ext
                from audit_list a left join
                leave_record l on a.leave_id = l.id left join
                user_info u on l.user_id = u.user_id
                where a.uid = $user_id and a.status = 1 $and
                order by a.leave_id desc
                limit $offset,$page
                ";
        }
        $rows = $this->get_defaut_dao()->find_by_sql($sql);
      //  print_r($rows);die();
        //var_dump($rows);
        if($role[$user_id]['role_id'] == 3 && !empty($and)){
            $sql_count = "select count(l.id) as count
                from leave_record l left join
                user_info u on l.user_id = u.user_id
                where l.status = '未审核' $and";
            //如果是HR搜索时
            $data['uroles'] = $role[$user_id]['role_id'];
        } else {
            $sql_count = "select count(a.uid) as count
                from audit_list a left join
                leave_record l on a.leave_id = l.id left join
                user_info u on l.user_id = u.user_id
                where a.uid = $user_id and a.status = 1 $and";
        }
        $data['rows'] = $rows;
        $count = $this->get_defaut_dao()->find_by_sql($sql_count);
        $data['count'] = $count[0]['count'];

        /*
        //获取BOSS id
        $this->get_boss_id();
        //判断是否为BOSS
        if($user_id != $this->boss_id){
            $or = " or (leave_time >=3 and r.b_user_id = $user_id) ";
        }
        else{
            $or = ' ';
        }

        //查询出差，每个部门都是独立的
        $adut_info = $this->get_trip_manage_ids($user_id);
        if(empty($adut_info)){
            $bigor = ' ';
        }
        else{
            $ids = '';
            foreach($adut_info as $s){
                $ids .= $s['department_id'].",";
            }
            $ids = rtrim($ids,",");
            $bigor = " or ( r.status = '未审核' and r.type ='出差' and u.department_id in({$ids})) ";
        }

        $sql = "SELECT rl.*,u.name,u.code,u.department_id,u.department_name,r.id,r.r_user_id,r.b_user_id,r.leave_time,r.type,r.leave_reason,r.start_time,r.end_time
                from leave_record r LEFT JOIN
                user_info u on r.user_id = u.user_id LEFT JOIN
                leave_record_log rl on  rl.leave_id = r.id
                where
                r.is_cancel = 0 and
                !(r.leave_reason='地铁故障' and r.type='迟到') and r.status = '未审核' and
                ((r.type !='出差' and (r.r_user_id = $user_id and rl.operator is null  $or ))  $bigor) $and
                order by r.apply_time desc
                limit $offset,$page";

        $rows = $this->get_defaut_dao()->find_by_sql($sql);

        foreach($rows as &$v){
            if($v['b_user_id'] == $user_id and $v['type'] !='出差'){
                $v['is_second'] = 1;
            }
        }

        $sql_count = "SELECT count(r.id) as count
                from leave_record r LEFT JOIN
                user_info u on r.user_id = u.user_id
                LEFT JOIN
                leave_record_log rl on rl.leave_id = r.id
                where
                r.is_cancel = 0 and
                !(r.leave_reason='地铁故障' and r.type='迟到') and r.status = '未审核' and
                ((r.type !='出差' and (r.r_user_id = $user_id and rl.operator is null $or )) $bigor) $and ";

        $count = $this->get_defaut_dao()->find_by_sql($sql_count);
        $data['rows'] = $rows;
        */
        return $data;
    }
    //得到未审批数字
    public function get_audit_cnt($uid){
        $sql_count = "select count(a.uid) as count
                from audit_list a left join
                leave_record l on a.leave_id = l.id left join
                user_info u on l.user_id = u.user_id
                where a.uid = $uid and a.status = 1 ";
        $count = $this->get_defaut_dao()->find_by_sql($sql_count);
        return $count[0]['count'];
    }
    /**
     * 得到用户为未审批的请假记录
     * @param int $uid
     */
    public function get_audit_count($uid){
        $where["(r_user_id=$uid AND audit_status=0)  OR (b_user_id=$uid AND audit_status=1) AND 1=?"] = 1;
        $where["status"]='未审核';
        $count = $this->get_defaut_dao()->find_count($where);
        return $count;
    }
    public function get_record_log($user_id){
        $rows = $this->get_leaverecordlog_dao()->find(array('operator'=>$user_id));
        return $rows;
    }

    //同意
    public function audit_apply($user_id,$leave_id,$params=array()){
        $this->session_act();
        $action = 2;
        $is_valid = $this->is_valid($user_id, $leave_id);
        if($is_valid){
            $info = $this->get_leave_info($leave_id);
            if($info['type']=='出差' || $info['type']=='公出'){
                //直接更新
                $this->get_defaut_dao()->update(array('status'=>'已批准','audit_status'=>1),array('id'=>$leave_id));
                $daily_bll = new Bll_Attendance_DailyReport();
                $daily_bll->make_leave_data($leave_id,2);
                $this->set_record_log($user_id, $action, $leave_id,$params['apply_msg']);
                //$this->get_audit_list_dao()->update(array('status'=>2),array('leave_id'=>$leave_id,'uid'=>$user_id));
                //凡出差申请，被批准后即邮件通知申请人+dl-hr；
                if($info['type']=='出差'){
                    $email_user_info = $this->get_user_info_by_id($info['user_id']);
                    $r_user_info = $this->get_user_info_by_id($info['r_user_id']);
                    apf_require_class("Tools_SendMail");
                    Tools_SendMail::get_instance()->send_on_business_travel_yes($email_user_info,$info);
                    $leavedetail = $this->get_trip_detail($leave_id);
                    Tools_SendMail::get_instance()->send_on_business_travel_yes_hr($email_user_info,$info,$leavedetail,$r_user_info);//发给hr
                }
            }
            else{//非出差类,需要一级领导或者二级领导批准
                $rows = $this->get_leaverecordlog_dao()->find(array('leave_id'=>$leave_id));
                //如果假期是产假或是产前假在user_info_ext.leave_status有标识 TODO最新的数据结构中不再需要这个方式
                apf_require_class("Bll_Attendance_UserExt");
                $userext = new Bll_Attendance_UserExt();
                $status_leave=0;
                if($info['type'] =='产假'|| $info['type'] =='产前假'){
                    $status_leave=$leave_id;
                }
                $userext->update_leave_status($user_id,$status_leave);
                $bll_role = new Bll_Attendance_Role();
                $audit_user_ids = $bll_role->get_sup_id($info['user_id'],array(1,2));
                if($info['leave_time'] >3){
                    //需要两个人审批
                    if(empty($rows)){//不需要验证
                        $up =array(
                                'last_touch'=>date("Y-m-d H:i:s"),
                                'audit_status'=>1,
                                );
                        if($audit_user_ids[2]==6932){//如果是二级审批人是 mike就直接通过
                            $up['status']='已批准';
                        }
                        $this->get_defaut_dao()->update($up,array('id'=>$leave_id));
                        $this->set_record_log($user_id, $action, $leave_id,$params['apply_msg']);

                        if($audit_user_ids[2]==6932){//需要拿到请假的状态
                            $daily_bll = new Bll_Attendance_DailyReport();
                            $daily_bll->make_leave_data($leave_id,2);
                        }
                        //发送邮件通知二级领导,mike直接跳过
                        $email_user_info = $this->get_user_info_by_id($info['user_id']);
                        if(($info['b_user_id'] != $this->get_boss_id())){
                            $to = $this->get_user_email($info['b_user_id']);
                            $unit = $info['type']=='公出' ? '小时':'天';
                            $title =  $info['type']."申请 - ".$email_user_info['name'];
                            $body  = "姓名:".$email_user_info['name']."<br>".
                                    "工号:".$email_user_info['code']."<br>".
                                    "起始日期:".$info['start_time']."<br>".
                                    "结束日期:".$info['end_time']."<br>".
                                    "请假时长:".$info['leave_time'].$unit."<br>".
                                    "请假类型:".$info['type']."<br>".
                                    "请假理由:".$info['leave_reason'].$info['leave_desc']."<br>";
                                    if($info['type']!='公出'){
                                        $body  .= "工作代理人:".$info['leave_agent']."<br>";
                                    }
                                    $body  .="请点击以下链接审批"."<br><a href ='".Tools_OAUrls::get_instance()->build_leave_detail_url($leave_id)."'>".Tools_OAUrls::get_instance()->build_leave_detail_url($leave_id)."</a><br>".
                                    "如需查看更多,请访问<br>".$this->passurl;
                            apf_require_class("Tools_SendMail");
                            $tools = Tools_SendMail::get_instance()->send($to, $title, $body);

                            //直接写入请假记录,处理邮件延迟问题
                            //$audit_list = array('uid'=>$info['b_user_id'],'leave_id'=>$leave_id,'status'=>1);
                            //$this->replace_record($audit_list);
                        }
                    }
                    else{
                        //验证自己是否已经审批过，做最后的更新操作,处理历史遗留问题，这步不做过滤
                        /**
                        foreach ($rows as $v){
                            if($v['operator'] == $user_id){
                                return false;
                            }
                        }
                        */
                        //做最后的更新操作 2代表是二级审批人
                        $this->get_defaut_dao()->update(array('status'=>'已批准','audit_status'=>2),array('id'=>$leave_id));
                        $daily_bll = new Bll_Attendance_DailyReport();
                        $daily_bll->make_leave_data($leave_id,2);
                        //$this->get_audit_list_dao()->update(array('status'=>2),array('leave_id'=>$leave_id,'uid'=>$user_id));
                        $this->set_record_log($user_id, $action, $leave_id,$params['apply_msg']);
                    }
                }
                else{
                    //一个人审批
                    if(empty($rows)){
                        $this->get_defaut_dao()->update(array('status'=>'已批准','audit_status'=>1),array('id'=>$leave_id));
                        $daily_bll = new Bll_Attendance_DailyReport();
                        $daily_bll->make_leave_data($leave_id,2);
                        $this->set_record_log($user_id, $action, $leave_id,$params['apply_msg']);
                        //$this->get_audit_list_dao()->update(array('status'=>2),array('leave_id'=>$leave_id,'uid'=>$user_id));
                        //TODO 最好增加回滚，三个同时进行的操作
                    }
                    else{
                        //已经审批过了
                        return FALSE;
                    }
                }
            }
        }
        else{
            return false;
        }
    }
    //拒绝
    public function aduit_reject($user_id,$leave_id,$params=array()){
        $action = 1;
        $is_valid = $this->is_valid($user_id, $leave_id);
        if($is_valid){
            $back = $this->get_defaut_dao()->update(array('status'=>'已驳回','audit_status'=>0),array('id'=>$leave_id));
            //如果是年假 驳回成功 返回年假天数 by coldarmy
            apf_require_class('Bll_Attendance_LeaveRecord');
            $bll = new Bll_Attendance_LeaveRecord();
            $record = $bll->get_leave_by_id($leave_id);
            if($back && $record['type'] == '年假') {
                 apf_require_class('Bll_Attendance_UserExt');
                 $uext = new Bll_Attendance_UserExt();
                 $leave_time = $record['leave_time'];
                 $leave_time = 0 - $leave_time;
                 $back = $uext->update_used_annual($record['user_id'], $leave_time);
            }
            $daily_bll = new Bll_Attendance_DailyReport();
            $daily_bll->make_leave_data($leave_id,3);
            $this->set_record_log($user_id, $action, $leave_id,$params['apply_msg']);
            //$this->get_audit_list_dao()->update(array('status'=>2),array('leave_id'=>$leave_id,'uid'=>$user_id));
            //当一个出差申请被其主管审批不通过，邮件通知申请人
            if($record['type']=='出差'){
                $email_user_info = $this->get_user_info_by_id($record['user_id']);
                apf_require_class("Tools_SendMail");
                Tools_SendMail::get_instance()->send_on_business_travel_no($email_user_info,$record);
            }
        }
        else{
            return false;
        }
    }
    //写入日志
    private function set_record_log($user_id,$action,$leave_id,$apply_msg=''){
        $updated = date("Y-m-d H:i:s",time());
        $array = array('operator'=>$user_id,'action'=>$action,'updated'=>$updated,'leave_id'=>$leave_id,'apply_msg'=>$apply_msg);
        $result = $this->get_leaverecordlog_dao()->insert($array);
        return $result;
    }
    //判断审批是否合法
    public function is_valid($user_id,$leave_id){
        $this->session_act();
        //绿色通道
        if($_SESSION['code']=='SHA001'){
            return true;
        }
        $info = $this->get_leave_info($leave_id);
        if($info['status'] == '未审核' and $info['type'] !='出差' and ($info['r_user_id']== $user_id or $info['b_user_id']==$user_id)){
            //合法
            return true;
        }
        elseif($info['status'] == '未审核' and $info['type'] =='出差'){
            $row = $this->get_tripmanager_dao()->find_row(array('user_id'=>$user_id));
            if($row['user_id'] == $user_id){
                return true;
            }
            else{
                return FALSE;
            }
        }
        else{
            return FALSE;
        }
    }

    //根据leave_id 获取请假状态信息
    public function get_leave_info($leave_id){
        $rows = $this->get_defaut_dao()->find_row(array('id'=>$leave_id));
        return $rows;
    }
    //更新audit_list
    public function update_audit_list($update,$where){
        return $this->get_audit_list_dao()->update($update,$where);
    }
    /**
     * 根据leave_id 获取出差详情
     */
    public function get_trip_detail($leave_id){
        $rows = $this->get_trip_detail_dao()->find(array('leave_id'=>$leave_id));
        return $rows;
    }
    private function get_trip_manage_ids($user_id){
        $ids = $this->get_tripmanager_dao()->find(array('user_id'=>$user_id));
        return $ids;
    }

    private function get_boss_id(){
        //TODO 可配置code
        $code = "SHA001";
        $row = $this->get_userinfo_dao()->find_row(array('code'=>$code));
        $this->boss_id = $row['user_id'];
        return $row['user_id'];
    }


    private function get_user_info(){
        $this->session_act();
        $this->user_info = $_SESSION;
        return $this->user_info;
    }

    private function get_user_email($user_id){
        $row = $this->get_userinfo_dao()->find_row(array('user_id'=>$user_id));
        $email = $row['email'];
        return $email;
    }

    /**
     * 根据leave_id 获取审批信息
     *
     */
    public function get_audit_by_leave_id($id){
        $result = $this->get_audit_list_dao()->find(array('leave_id'=>$id));
        return $result;
    }

    /**
     *根据用户id获取用户信息
     * @param int $user_id
     * @return array
     */
    private function get_user_info_by_id($user_id){
        $row = $this->get_userinfo_dao()->find_row(array('user_id'=>$user_id));
        return $row;
    }

    /**
     *请假记录写入到记录列表
     * @param array $date('uid'=>$date['uid'],'leave_id'=>$date['leave_id'],'status'=>$date['staus']);
     */
    public function replace_record($date){
        $sql = "REPlACE INTO audit_list(uid,leave_id,status) values('{$date['uid']}','{$date['leave_id']}','{$date['status']}')";
        return $this->get_defaut_dao()->execute($sql);
    }
    /**
     *
     */
    private function get_defaut_dao(){
        return $this->get_dao('DAO_Attendance_LeaveRecord');
    }
    private function get_tripmanager_dao(){
        return $this->get_dao('DAO_Attendance_TripManager');
    }
    private function get_userinfo_dao(){
        return $this->get_dao('DAO_Attendance_UserInfo');
    }
    private function get_leaverecordlog_dao(){
        return $this->get_dao('DAO_Attendance_LeaveRecordLog');
    }
    private function get_audit_list_dao(){
        return $this->get_dao('DAO_Attendance_AuditList');
    }
    private function get_trip_detail_dao(){
        return $this->get_dao('DAO_Attendance_TripDetail');
    }
}
